package com.wo.cloud.cloud.filter;

import cn.hutool.core.util.StrUtil;
import com.wo.cloud.core.constant.TenantConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import com.wo.cloud.core.context.TenantContextHolder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/13 9:26
 * Description: tenant 上下文过滤器 （过滤器只对web请求进行过滤处理，而aop对所有请求都会进行拦截处理）
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        try {
            // 从header中获取tenantId
            String tenantId = httpServletRequest.getHeader(TenantConstant.TENANT_ID_HEADER);

            if (StrUtil.isBlank(tenantId)) {
                tenantId = httpServletRequest.getParameter(TenantConstant.TENANT_ID_PARAM);
            }
            System.out.println("tenant: "+ tenantId);

            // TODO: 逻辑不通
            if (StrUtil.isNotBlank(tenantId)) {
                TenantContextHolder.setTenantId(tenantId);
            } else {
                // 判断是否是服务之间调用，
                if (StrUtil.isBlank(TenantContextHolder.getTenantId())) {
                    TenantContextHolder.setTenantId(TenantConstant.TENANT_ID_DEFAULT);
                }
            }
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } finally {
            // 关闭上下文
            TenantContextHolder.clear();
        }
    }
}
